var api = require('../../utils/api.js');
//index.js
//获取应用实例
var app = getApp()
Page({
  data: {
    motto: 'Hello ',
    userInfo: {},
    sessionToken: ''
  },
  //事件处理函数
  bindViewTap: function () {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  onLoad: function () {
    console.log('onLoad')
    var that = this
    //调用应用实例的方法获取全局数据
    app.getUserInfo(function (userInfo) {
      //更新数据
      that.setData({
        userInfo: userInfo
      })
    })


    wx.login({
      success: function (res) {
        if (res.code) {
          //发起网络请求
          wx.request({
            url: api.getSessionKey(),
            data: {
              code: res.code
            },
            dataType: "json",
            success: function (res) {
              console.log("token:" + res.data.sessionToken)
              that.setData({
                sessionToken: res.data.sessionToken
              })

              wx.getUserInfo({
                withCredentials: true,
                success: function (res) {
                  var userInfo = res.userInfo
                  var nickName = userInfo.nickName
                  var avatarUrl = userInfo.avatarUrl
                  var gender = userInfo.gender //性别 0：未知、1：男、2：女
                  var province = userInfo.province
                  var city = userInfo.city
                  var country = userInfo.country
                  console.log("-----:" + res.encryptedData)
                  console.log(res.iv)
                  console.log(res.rawData)
                  console.log(res.signature)
                  if (that.data.sessionToken != '') {
                    //发起网络请求
                    wx.request({
                      url: api.register(),
                      method: 'POST',
                      header: {
                        'content-type': 'application/x-www-form-urlencoded'
                      },
                      data: {
                        encryptedData: res.encryptedData,
                        iv: res.iv,
                        sessionToken: that.data.sessionToken
                      },
                      dataType: "json",
                      success: function (res) {
                        console.log(res.data.status)
                        if (res.data.status == 'success') {

                          wx.setStorageSync('token', res.data.token)
                        }
                      }
                    })
                  }

                }
              })
            }
          })
        } else {
          console.log('获取用户登录态失败！' + res.errMsg)
        }
      }
    });

  }
})
